package com.yf.course.modules.course.utils;

import javax.sound.sampled.*;
import java.util.Arrays;

public class MicrophoneRecorder {
    private TargetDataLine microphone;

    // 初始化麦克风
    public void startRecording() throws LineUnavailableException {
        AudioFormat format = new AudioFormat(16000, 16, 1, true, false);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

        if (!AudioSystem.isLineSupported(info)) {
            throw new LineUnavailableException("不支持16k/16bit麦克风");
        }

        microphone = (TargetDataLine) AudioSystem.getLine(info);
        microphone.open(format);
        microphone.start();
    }

    // 实时读取音频数据
    public byte[] readAudioChunk() {
        byte[] buffer = new byte[1280]; // 每40ms的数据量 (16000Hz * 16bit * 40ms / 8 = 1280字节)
        int bytesRead = microphone.read(buffer, 0, buffer.length);
        return Arrays.copyOf(buffer, bytesRead);
    }

    public void stopRecording() {
        if (microphone != null) {
            microphone.stop();
            microphone.close();
        }
    }
}
